package sopraim.presenter.servlets;

import sopraim.presenter.filter.ConnectionFilter;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import sopraim.entity.User;
import sopraim.presenter.services.UserService;

public class ConnectionServlet extends HttpServlet {
    private static final long serialVersionUID = -9135210782075614862L;
    private static final String connectionPage = "/WEB-INF/Connection.jsp";
    private static final String homePage = "/WEB-INF/Home.jsp";
    public static final String ATT_USER = "user";
    public static String url;
    private final UserService userService = new UserService();
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.goToConnectionPage(request,response);
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        User user;
        String username = request.getParameter("username");
        String passwd = request.getParameter("password");
        try {
            
            user = userService.connect(username,passwd);
            /* Authorize connection */
            HttpSession session = request.getSession();
            session.setAttribute(ATT_USER, user);
            session.setAttribute(ConnectionFilter.USER_SESSION_FIELD, true);
            url = request.getRequestURL().toString();
            request.getRequestDispatcher(homePage)
                    .forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("errors", ex.getMessage());
            this.goToConnectionPage(request,response);
        }
        
        
        
    }
    
    private void goToConnectionPage(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException
    {
        request.getRequestDispatcher(connectionPage)
                .forward(request, response);
    }
}
